%% Author : lichuang 

-module(echubby_quorum_server).
-behaviour(gen_fsm).

-include("echubby.hrl").
-include("quorum_peer_pb.hrl").

-export([start/0,
	 stop/1]).
%% gen_fsm callbacks
-export([init/1,
    handle_event/3,
    handle_sync_event/4,
    handle_info/3,
    terminate/3,
    code_change/4]).

start() ->
  gen_fsm:start(?MODULE, [], []).

stop(Pid) ->
  gen_fsm:send_all_state_event(Pid, stop).

init(_Args) ->
  Msg = #notification{leader = 1,
    gxid   = 2,
    epoch  = 3,
    state  = 1,
    server_id = 5},
  gen_server:cast(echubby_quorum_manager, connect_to_other_servers),
  gen_server:cast(echubby_quorum_manager, Msg),
  {ok, looking_for_leader, []}.

looking_for_leader(_Args, State) ->
  {next_state, leading, State}.

leading(_Args, State) ->
  {next_state, leading, State}.

following(_Args, State) ->
  {next_state, leading, State}.

handle_event(stop, _StateName, StateData) ->
  {stop, normal, StateData};
handle_event(_Event, StateName, StateData) ->
  {next_state, StateName, StateData}.

handle_sync_event(_Event, _From, StateName, StateData) ->
  Reply = ok,
  {reply, Reply, StateName, StateData}.

handle_info(_Info, StateName, StateData) ->
  {next_state, StateName, StateData}.

terminate(_Reason, _StateName, _StateData) ->
  ok.

code_change(_OldVsn, StateName, StateData, _Extra) ->
  {next_state, StateName, StateData}.
